package com.huadao.cart_ccs.experiment.preprocessing;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.daolion.utils.log.LogUploadUtils;
import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseDialogFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.ParamsPreferences;
import com.huadao.cart_ccs.common.TimeUtil;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.common.dialog.IDialogResultListener;
import com.huadao.cart_ccs.experiment.sterilization.UltravioletSterilizationActivity;
import com.huadao.cart_ccs.main.CartApplication;
import com.huadao.cart_ccs.widget.MultiStateTextView;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

//预处理
public class PreprocessingDF extends BaseDialogFragment implements PreprocessingContract.IPreprocessingView {

    @BindView(R.id.cb_input_pump) MultiStateTextView cbInputPump;
    @BindView(R.id.cb_circulating_pump) MultiStateTextView cbCirculatingPump;
    @BindView(R.id.cb_waste_pump) MultiStateTextView cbWastePump;
    @BindView(R.id.cb_reclaim_pump) MultiStateTextView cbReclaimPump;
    @BindView(R.id.cb_CO2) MultiStateTextView cbCO2;
    @BindView(R.id.cb_O2) MultiStateTextView cbO2;
    @BindView(R.id.cb_temperature) MultiStateTextView cbTemperature;
    @BindView(R.id.cb_weight) MultiStateTextView cbWeight;
    @BindView(R.id.cb_liquid_level_meter) MultiStateTextView cbLiquidLevelMeter;
    @BindView(R.id.btn_detect) Button btnDetect;
    @BindView(R.id.btn_clean) Button btnClean;
    @BindView(R.id.btn_install) Button btnInstall;
    @BindView(R.id.btn_into_culture) Button btn_into_culture;
    @BindView(R.id.tv_cleaner) TextView tv_cleaner;
    @BindView(R.id.tv_clean_time) TextView tv_clean_time;
    @BindView(R.id.btn_open_door_manual) Button btn_open_door_manual;
    @BindView(R.id.tv_installer) TextView tv_installer;
    @BindView(R.id.tv_installer_time) TextView tv_installer_time;
    @BindView(R.id.btn_close_door_manual) Button btn_close_door_manual;

    private PreprocessingPresenter preprocessingPresenter;
    private boolean isStep1Finish;
    private boolean isStep2Finish;
    private boolean isStep3Finish;

    @Override
    protected BasePresenter getPresenter() {
        return preprocessingPresenter;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialogfrag_preprocessing;
    }

    @Override
    protected void onInit() {
        preprocessingPresenter = new PreprocessingPresenter(this);
        setTitle(getString(R.string.preprocessing));
        setCloseIconsVisibility(View.GONE);
        tv_cleaner.setText(CartApplication.getInstance().getOperator());
        tv_installer.setText(CartApplication.getInstance().getOperator());
        initStep1();
    }

    private void initStep1() {
        preprocessingPresenter.checkAll();
        btnClean.setEnabled(false);
        btnInstall.setEnabled(false);
    }

    private void initStep2() {
        btnClean.setEnabled(true);
    }

    private void initStep3() {
        btnInstall.setEnabled(true);
    }

    private void initGotoCulture() {
        btn_into_culture.setEnabled(true);
    }

    @OnClick({R.id.btn_open_door_manual, R.id.btn_close_door_manual, R.id.btn_detect, R.id.btn_clean, R.id.btn_install, R.id.door, R.id.btn_into_culture})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_open_door_manual:
                preprocessingPresenter.openDoor();
                break;
            case R.id.btn_close_door_manual:
                preprocessingPresenter.closeDoor();
                break;
            case R.id.btn_detect:
                //检测设备前，全部重置
                resetAllDevices();
                preprocessingPresenter.checkAll();
                break;
            case R.id.btn_into_culture:
                //                String err=checkSteps();
                //                if(err!=null){
                //                    showDialogMsg(err);
                //                    return;
                //                }
                //此界面所有步骤完成后，去皮，保存下位机返回的AD值，最后进入下个界面。
                //                preprocessingPresenter.initPeel();
                //                onInitPeelSucc(new byte[]{0,0,0,0});
                toUltravioletSterilization();
                break;
            case R.id.btn_clean:
                tv_clean_time.setText(TimeUtil.log_sdf.format(new Date()));
                btnClean.setText("清洁确认完成");
                btnClean.setBackgroundResource(R.drawable.bg_green_corner);
                btnClean.setEnabled(false);
                isStep2Finish = true;
                initStep3();
                break;
            case R.id.btn_install:
                tv_installer_time.setText(TimeUtil.log_sdf.format(new Date()));
                btnInstall.setText("安装确认完成");
                btnInstall.setBackgroundResource(R.drawable.bg_green_corner);
                btnInstall.setEnabled(false);
                isStep3Finish = true;
                DialogFragmentHelper.showConfirmDialog(getActivity(), "", "是否关门", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            preprocessingPresenter.closeDoor();
                            //安装完成后，首次称重的值，作为之后称重值的参考值
                            //                            preprocessingPresenter.firstWeight();
                        } else if (result == DialogInterface.BUTTON_NEGATIVE) {

                        }
                    }
                }, true);
                openEnvironment();
                initGotoCulture();
                break;
            case R.id.door:
                DialogFragmentHelper
                        .showTwoOperateDialog(getActivity(), getString(R.string.door), null, R.string.open_door, R.string.close_door, result -> {
                            if (result == DialogInterface.BUTTON_POSITIVE) {
                                preprocessingPresenter.openDoor();
                            } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                                preprocessingPresenter.closeDoor();
                            }
                        }, true);
                break;
        }
    }

    private void openEnvironment() {
        preprocessingPresenter.setCO2();
        preprocessingPresenter.setO2();
        preprocessingPresenter.setTemperature();
        preprocessingPresenter.openAirPump();
    }

    private String checkSteps() {
        String err = null;
        if (!isStep1Finish) {
            err = "设备自检未完成";
        } else if (!isStep2Finish) {
            err = "请确认设备清洁完成";
        } else if (!isStep3Finish) {
            err = "请确认设备安装完成";
        }
        return err;
    }

    private void resetAllDevices() {
        cbInputPump.setState(MultiStateTextView.STATE_DEFAULT);
        cbCirculatingPump.setState(MultiStateTextView.STATE_DEFAULT);
        cbWastePump.setState(MultiStateTextView.STATE_DEFAULT);
        cbReclaimPump.setState(MultiStateTextView.STATE_DEFAULT);
        cbCO2.setState(MultiStateTextView.STATE_DEFAULT);
        cbO2.setState(MultiStateTextView.STATE_DEFAULT);
        cbTemperature.setState(MultiStateTextView.STATE_DEFAULT);
        cbWeight.setState(MultiStateTextView.STATE_DEFAULT);
        cbLiquidLevelMeter.setState(MultiStateTextView.STATE_DEFAULT);
    }

    @Override
    public void onCheckInputPump(int state) {
        cbInputPump.setState(state);
    }

    @Override
    public void onCheckCiriclingPump(int state) {
        cbCirculatingPump.setState(state);
    }

    @Override
    public void onCheckWastePump(int state) {
        cbWastePump.setState(state);
    }

    @Override
    public void onCheckReclaimPump(int state) {
        cbReclaimPump.setState(state);
    }

    @Override
    public void onCheckLiquidLevelMeter(int state) {
        cbLiquidLevelMeter.setState(state);
    }

    @Override
    public void summaryDeviceSelfCheck() {
        String err = isDevicesAllOK();
        if (err == null) {
            isStep1Finish = true;
            btnDetect.setText("设备正常");
            btnDetect.setEnabled(false);
            btnDetect.setBackgroundResource(R.drawable.bg_green_corner);
            initStep2();
            //自检完成后提示开门清洁
            DialogFragmentHelper.showConfirmDialog(getActivity(), "", "是否开门清洁设备", new IDialogResultListener<Integer>() {
                @Override
                public void onDataResult(Integer result) {
                    if (result == DialogInterface.BUTTON_POSITIVE) {
                        preprocessingPresenter.openDoor();
                    } else if (result == DialogInterface.BUTTON_NEGATIVE) {

                    }
                }
            }, true);
        } else {
            showDialogMsg(err);
            btnDetect.setBackgroundResource(R.drawable.shape_preprocess_button_error);
            btnDetect.setText(R.string.reDetect);
        }
        //上传日志到到百度空间;
        LogUploadUtils.getInstance().uploadLogData(getContext());
    }

    @Override
    public void onCheckWeight(int state) {
        cbWeight.setState(state);
    }

    @Override
    public void onCheckTemperature(int state) {
        cbTemperature.setState(state);
    }

    @Override
    public void onCheckCO2(int state) {
        cbCO2.setState(state);
    }

    @Override
    public void onCheckO2(int state) {
        cbO2.setState(state);
    }

    @Override
    public void onReadDoorSucc(String status) {
        showToast(status);
    }

    @Override
    public void onOpenDoorSucc() {
        showToast("正在开门");
    }

    @Override
    public void onCloseDoorSucc() {
        showToast("正在关门");
    }

    @Override
    public void onInitPeelSucc(byte[] ad) {
        ParamsPreferences.getInstance().setADCommit(ad);
        toUltravioletSterilization();
    }

    private void toUltravioletSterilization() {
        Intent intent = new Intent(getActivity(), UltravioletSterilizationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("sterilizationTime", 30 * 60);
        bundle.putInt("leftChangeAirSecond", preprocessingPresenter.getLeftChangeAirTime());
        intent.putExtras(bundle);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void onFirstWeight(double weight) {
        showToast("成功获取称重参考值:" + (int) weight + "g");
        //        ParamsPreferences.getInstance().setReferenceWeightCommit(weight);
    }

    @Override
    public void onFirstWeightFailed() {
        showToast("获取称重参考值失败");
    }

    @Override
    public void onSetCO2() {
        showToast("CO2设置成功");
    }

    @Override
    public void onSetO2() {
        showToast("O2设置成功");
    }

    @Override
    public void onSetTemperature() {
        showToast("温度设置成功");
    }

    private synchronized String isDevicesAllOK() {
        StringBuilder err = new StringBuilder();
        if (cbInputPump.getState() == MultiStateTextView.STATE_OK) {
            //设备正常不报错
        } else if (cbInputPump.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("进液泵异常\n");
        } else {
            err.append("进液泵未知\n");
        }

        if (cbCirculatingPump.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbCirculatingPump.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("循环泵异常\n");
        } else {
            err.append("循环泵未知\n");
        }

        if (cbWastePump.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbWastePump.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("废液泵异常\n");
        } else {
            err.append("废液泵未知\n");
        }


        if (cbReclaimPump.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbReclaimPump.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("罐装泵异常\n");
        } else {
            err.append("罐装泵未知\n");
        }

        if (cbCO2.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbCO2.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("CO2传感器异常\n");
        } else {
            err.append("CO2传感器未知\n");
        }

        if (cbO2.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbO2.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("O2传感器异常\n");
        } else {
            err.append("O2传感器未知\n");
        }

        if (cbTemperature.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbTemperature.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("温度传感器异常\n");
        } else {
            err.append("温度传感器未知\n");
        }

        if (cbWeight.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbWeight.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("电子秤异常\n");
        } else {
            err.append("电子秤未知\n");
        }

        if (cbLiquidLevelMeter.getState() == MultiStateTextView.STATE_OK) {

        } else if (cbLiquidLevelMeter.getState() == MultiStateTextView.STATE_ERROR) {
            err.append("液位仪异常");
        } else {
            err.append("液位仪未知");
        }

        return err.length() == 0 ? null : err.toString();
    }


    private void showDialogMsg(String msg) {
        DialogFragmentHelper.showMultiLineMessageDialog(getActivity(), null, msg);
    }
}
